<!--
*@Author: QWP
*@Description: 综合预警
*@Date: 2024-07-18 14:05:35
-->
<template>
  <u-card :title="h('div', {
    class: 'f-flex-row f-focus-title',
    style: { cursor: 'pointer', },
    onClick: () => titleClick()
  }, [
    h('span', '关注企业预警情况'),
    h(RightOutlined, { style: { marginLeft: '6px' } })
  ])" :loading="loading">
    <template #extra>
      <a-space style="float: right">
        <div class="u-focus-firm-index-change">
          <LeftOutlined @click="exchange('up')" />
        </div>
        <div class="u-focus-firm-index-change">
          <RightOutlined @click="exchange('next')" />
        </div>
      </a-space>
    </template>
    <a-row class="f-padding-16 f-margin-b12 f-margin-t6 f-item-hover-bg1"
      style="background-color: #F5F6F6; border-radius: 16px">
      <a-space size="middle" @click="firmClick"  class="f-none-select">
        <a-image :src="urlFile('index/focus_qy.png')" :preview="false"></a-image>
        <a-space direction="vertical">
          <span class="u-focus-firm-name">{{ getKeyValue('companyName') }}</span>
          <a-space size="large" class="u-focus-firm-info">
            <span>行业类型：{{ getKeyValue('companyType') }}</span>
            <span>当前风险等级：
              <a-tag :color="levMainColor[numberC(getKeyValue('riskLevel')) - 1]">
                {{ levelText(getKeyValue('riskLevel')) }}级
              </a-tag>
            </span>
          </a-space>
        </a-space>
      </a-space>
    </a-row>
    <!-- @click.stop="firmClick" -->
    <template v-if="firmInfo.length != 0">
      <div ref="chartRef" style="width: 100%; height: 230px;cursor: pointer"></div>
    </template>
    <template v-else>
      <a-empty>
        <template #description>
          暂无关注企业数据
        </template>
      </a-empty>
    </template>
  </u-card>

  <!-- 企业预警信息 -->
  <u-dialog title="企业预警信息" wrap-class-name="full-modal" width="100px" v-model:open="showDetial" :hideBtns="['submit']">
    <SumWarningIndex type="index" @focusChange="regetData"/>
  </u-dialog>
  
  <!-- 企业信息详情 -->
  <u-dialog title="企业信息详情" width="100px" wrap-class-name="full-modal" v-model:open="showFirmDetial"
    :hideBtns="['submit']">
    <FirmWarninGDetial :show="showFirmDetial" :params="currentRow" />
  </u-dialog>

</template>

<script lang='ts' setup>
import { ref, reactive, computed, watch, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useHomeStore } from '@/store'
import { storeToRefs } from 'pinia'
import { getColor, levMainColor } from '@/views/index/emergencyIndex/data'
import USegmented from '@/views/index/emergencyIndex/component/segmented/Index.vue'
import { ColumnProps } from 'ant-design-vue/es/table'
import { ThunderboltOutlined, RightOutlined } from '@ant-design/icons-vue'
import { urlFile, numberC, nullC, alertC, messageC } from '@/util/common'
import { throttle } from '@/util/format.ts'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import SumWarningIndex from '@/views/oa/warning/sumWarning/Index.vue'
import FirmWarninGDetial from './FirmWarninGDetial.vue'
import * as sumWarningApi from '@/service/emergency/sumWarning'
import { debounce } from 'lodash'

const router = useRouter();
const emits = defineEmits(['focusChange'])
const { activeTabMenu } = storeToRefs(useHomeStore())

const chartDataResult = ref([])

let currentRow = ref({})
let currenIndex = ref<number>(0)
const loading = ref<boolean>(false)
const firmInfo = ref<any[]>([])

// 重新加载数据
const regetData = async (mineId) => {
  getSearch()
  if(mineId == getKeyValue('mineId') || !getKeyValue('mineId')) {
    await getWarnDeteQuery(getKeyValue('mineId'))
    initCharts()
  }
}

// 列表查询
const getSearch = async () => {
  loading.value = true;
  try {
    const res = await sumWarningApi.getCompany({
      current: 1,
      size: 500,
      model: { keywords: null, isAttention: 1, },
    })
    if (res.code == 0) {
      let tData = res.data.records || []
      let result = {}
      tData.forEach(item => {
        let key = item.companyType + '-' + item.riskLevel + '-' + item.companyName
        if (!result[key]) result[key] = []
        result[key].push(item)
      })

      firmInfo.value = []
      for (let key in result) {
        firmInfo.value.push(result[key][0])
      }
    } else {
      messageC(res.msg, 'warning')
    }
  } catch (error) { }
  loading.value = false;
}

//根据属性关键字查询数据
const getKeyValue = (key: string) => {
  if (firmInfo.value.length != 0) {
    currentRow.value = firmInfo.value[currenIndex.value]
  }
  return firmInfo.value.length == 0 ? '' : firmInfo.value[currenIndex.value][key]
}

const levelText = (riskLevel) => {
  let text = { 1: '一', '2': '二', 3: '三', 4: '四' }
  return nullC(text[riskLevel])
}

// 根据id查询折线图数据
const getWarnDeteQuery = async (mineId?: string) => {
  if(!mineId) {
    return
  }
  //日期统计
  chartDataResult.value = []
  const result = await sumWarningApi.getWarnDete(mineId)

  if (result.code == 0) {
    chartDataResult.value = result.data
    chartDataResult.value.map(e => {
      e.MONTH = dayjs(e.MONTH).format('M')
    })
  }
}

// 图表
const chartData = ref([])
let arrList = ref([])
const chartRef = ref<HTMLElement>()
const initCharts = () => {
  chartData.value.splice(0, chartData.value.length);
  let nowMounth = dayjs().format('M');
  let levels = ['一级', '二级', '三级', '四级'];
  let months = [];
  for (let i = 1;i <= nowMounth;i++) {
    months.push(i)
  }


  levels.forEach(item => {
    arrList.value = []
    months.forEach(index => {
      let filermonth = chartDataResult.value.filter(i => i.MONTH == index.toString());
      let fileLeve = [0, ...filermonth.filter(i => i.WARN_LEVEL == item).map(i => i.COUNT)].reduce((a, b) => numberC(a) + numberC(b))
      arrList.value.push(fileLeve)
    })
    chartData.value.push({
      name: item, type: 'line', data: arrList.value
    })
  })

  try {
    var myChart = echarts.init(chartRef.value);
  
    const option = {
      color: ["#FF4D4F", "#FF8940", "#FAB410", "#1890FF"],
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: levels,
        right: 0,
        itemGap: 30,
        top: '10%',
        orient: 'vertical'
      },
      grid: {
        top: '10',
        left: '3%',
        right: '16%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: months.map(i => i + '月')
      },
      yAxis: {
        type: 'value'
      },
      series: chartData.value
    };
  
    option && myChart.setOption(option);
  
    window.addEventListener('resize', () => {
      setTimeout(() => {
        myChart.resize()
      }, 100)
    })
  }
  catch(e) {}
}

// 卡片标题的点击
let showDetial = ref<boolean>(false)
const titleClick = () => {
  showDetial.value = true;
}

// 点击企业和图表的跳转
let showFirmDetial = ref<boolean>(false)
const firmClick = () => {
  if(firmInfo.value.length == 0) {
    messageC("暂无关注企业可查看!");
    return
  }
  showFirmDetial.value = true;
}

// 切换
const exchange = async (type: string) => {
  let currentValue = currenIndex.value;
  if (type == 'up') {
    currenIndex.value = currentValue - 1 < 0 ? firmInfo.value.length - 1 : currentValue - 1;
  }
  else if (type == 'next') {
    currenIndex.value = currentValue + 1 > firmInfo.value.length - 1 ? 0 : currentValue + 1
  }

  await getWarnDeteQuery(getKeyValue('mineId'))
  initCharts()
}

const test = () => {
}

onMounted(async () => {
  await getSearch()
  await getWarnDeteQuery(getKeyValue('mineId'))
  initCharts()
})

watch(() => activeTabMenu, (nval, olva) => {
  if(nval.value == '0') {
    getSearch(0)
  }
}, { deep: true })


</script>

<style lang='scss' scoped>
.u-focus-firm-name {
  font-family: PingFang SC, PingFang SC;
  font-weight: 600;
  font-size: var(--font-size-level-2);
  color: #333333;
}

.u-focus-firm-info {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: var(--font-size-level-1);
}

.u-focus-firm-index-change {
  width: 32px;
  height: 32px;
  background: #1890ff;
  border-radius: 4px;
  text-align: center;
  line-height: 32px;
  color: #fff;

  &:hover {
    background-color: rgba(26, 144, 255, .8);
  }
}

.f-focus-title {
  &:hover {
    color: #1890ff;
  }
}

</style>